/* eslint-disable array-callback-return */
import React from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Spin, Select, message, Row, Col, Table, DatePicker } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import { isRepeat } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { Description } = DescriptionList;
const { MonthPicker } = DatePicker;

@connect(({ redass, loading }) => ({
  loading: loading.models.redass,
  redass,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      deduTaskId: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const query = queryString.parse(location.search);
    // 获取详情信息
    dispatch({
      type: 'redass/fetchAssDetail',
      payload: query.deduTaskId ? { deduTaskId: query.deduTaskId } : { sendId: query.sendId },
    });
    this.setState({ deduTaskId: query.deduTaskId || null });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const resetAdjustInfo = {
      assList: [], // 	雇员所有险种
      responseDeduAssBaseDto: {}, // 基本信息
      responseDeduAssSendDto: {}, // 派单信息
      responseHaveAssDtos: [], // 已有险种列表
      RemoveRsnList: [], // 离职原因
      tableId: 1,
      assInfoDtos: [{ id: 0, ass: undefined, endDate: undefined, assList: [] }], // 	减少险种集合
    };
    dispatch({
      type: 'redass/updateModelData',
      payload: { ...resetAdjustInfo },
    });
  }

  // 选择业务结束日期
  selectEndDate = (date, dateString, id) => {
    const {
      redass: { assInfoDtos },
      dispatch,
    } = this.props;
    // 解析当前日期格式（每月的最后一天）
    const str = moment(date).format('YYYY-MM');
    const arr = str.split('-');
    // eslint-disable-next-line camelcase
    const new_date = new Date(arr[0], arr[1], 1);
    assInfoDtos.map((item, index) => {
      if (item.id === id) {
        const lastDay = new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate();
        assInfoDtos[index].endDate = `${str}-${lastDay}`;
        assInfoDtos[index].lastDay = lastDay;
      }
    });
    dispatch({
      type: 'redass/updateModelData',
      payload: {
        assInfoDtos: [...assInfoDtos],
      },
    });
  };

  // 添加列表
  addList = () => {
    const {
      dispatch,
      redass: { tableId, assList, assInfoDtos },
    } = this.props;
    const newData = {
      id: tableId,
      ass: undefined,
      endDate: undefined,
      assList,
    };
    dispatch({
      type: 'redass/updateModelData',
      payload: {
        assInfoDtos: [...assInfoDtos, newData],
        tableId: tableId + 1,
      },
    });
  };

  // 删除列表
  deleteList = id => {
    const {
      dispatch,
      redass: { assInfoDtos },
    } = this.props;
    dispatch({
      type: 'redass/updateModelData',
      payload: { assInfoDtos: assInfoDtos.filter(item => item.id !== id) },
    });
  };

  // 提价数据
  submit = () => {
    const { dispatch, form, redass } = this.props;
    const { deduTaskId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.assInfoDtos) {
          const assInfoDtos = [];
          const assList = [];
          const temp = values;
          // eslint-disable-next-line no-unused-vars
          Object.entries(values.assInfoDtos).forEach(([_, value]) => {
            const obj = value;
            redass.assInfoDtos.forEach((item, index) => {
              if (value.id === item.id) {
                obj.endDate = `${moment(redass.assInfoDtos[index].endDate).format('YYYY-MM')}-${
                  item.lastDay
                }`;
                delete obj.id;
                assInfoDtos.push(value);
              }
            });
            if (value.ass && value.ass.length) {
              value.ass.forEach(ass => {
                assList.push({ ass });
              });
            }
          });
          if (isRepeat(assList, 'ass')) {
            message.warning('所选险种名称重复，请重新选择！');
            return;
          }
          temp.assInfoDtos = assInfoDtos;
          dispatch({
            type: 'redass/submit',
            payload: { deduTaskId, values },
          });
        } else {
          message.warning('请添加减少险种配置！');
        }
      }
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      redass: {
        responseDeduAssBaseDto, // 基本信息
        responseDeduAssSendDto, // 派单信息
        responseHaveAssDtos, // 已有险种列表
        RemoveRsnList,
        assInfoDtos,
        responseDeduAssDto,
      },
    } = this.props;
    const { deduTaskId } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    // 未修改业务结束日期
    // if(this.state.isChange){
    //   assInfoDtos.forEach((item, index) => {
    //     item.endDate = moment(moment(item.endDate).format('YYYY-MM-DD'), 'YYYY-MM-DD');
    //   })
    // }
    const assColumns = [
      {
        title: '险种',
        dataIndex: 'assName',
        align: 'center',
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        align: 'center',
      },
      {
        title: '执行方',
        dataIndex: 'execTypeName',
        align: 'center',
      },
      {
        title: '缴费方式',
        dataIndex: 'payWayName',
        align: 'center',
      },
      {
        title: '缴费账户',
        dataIndex: 'accoName',
        align: 'center',
      },
      {
        title: '社保组合',
        dataIndex: 'grpIdName',
        align: 'center',
      },
    ];

    return (
      <Form>
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>派单信息</span>}
              style={{ border: 'none' }}
            >
              <DescriptionList style={{ marginBottom: 24 }}>
                <Description term="签约方">
                  {responseDeduAssSendDto.sendCorpName || '--'}
                </Description>
                <Description term="客户名称">{responseDeduAssSendDto.custName || '--'}</Description>
                <Description term="商务合同">
                  {responseDeduAssSendDto.custContName || '--'}
                </Description>
                <Description term="报价单">{responseDeduAssSendDto.quoName || '--'}</Description>
                <Description term="派单时间">
                  {(responseDeduAssSendDto.sendDate &&
                    moment(responseDeduAssSendDto.sendDate).format('YYYY-MM-DD HH:mm')) ||
                    '--'}
                </Description>
              </DescriptionList>
            </Card>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>}
              style={{ border: 'none' }}
            >
              <DescriptionList style={{ marginBottom: 24 }}>
                <Description term="姓名">{responseDeduAssBaseDto.empName || '--'}</Description>
                <Description term="证件类型">
                  {responseDeduAssBaseDto.idTypeName || '--'}
                </Description>
                <Description term="证件号">{responseDeduAssBaseDto.idCode || '--'}</Description>
                <Description term="性别">{responseDeduAssBaseDto.genderName || '--'}</Description>
                <Description term="国籍">{responseDeduAssBaseDto.nationName || '--'}</Description>
                <Description term="出生日期">
                  {(responseDeduAssBaseDto.birthDate &&
                    moment(responseDeduAssBaseDto.birthDate).format('YYYY-MM-DD')) ||
                    '--'}
                </Description>
                <Description term="电话">{responseDeduAssBaseDto.mobile || '--'}</Description>
                <Description term="员工邮箱">{responseDeduAssBaseDto.email || '--'}</Description>
              </DescriptionList>
            </Card>
            {!deduTaskId && (
              <Card
                title={<span style={{ fontWeight: 'bolder' }}>已有社保信息</span>}
                style={{ border: 'none' }}
              >
                <Table
                  columns={assColumns}
                  dataSource={responseHaveAssDtos}
                  rowKey={(_, index) => index}
                  bordered
                  size="middle"
                  pagination={false}
                />
              </Card>
            )}
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>减少险种</span>}
              style={{ marginBottom: 16, border: 'none' }}
            >
              <Row gutter={16}>
                <Col span={8}>
                  <FormItem label="停做原因" {...formItemLayout}>
                    {getFieldDecorator('deduReason', {
                      rules: [{ required: false, message: '请选择' }],
                      initialValue: responseDeduAssDto.deduReason,
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        showSearch
                        optionFilterProp="children"
                      >
                        {RemoveRsnList.map(item => (
                          <Option key={item.rsgnRsnId} value={item.rsgnRsnId}>
                            {item.rsgnRsnName}
                          </Option>
                        ))}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
              {assInfoDtos.map((item, index) => (
                <Row gutter={16} key={item.id}>
                  <FormItem style={{ display: 'none' }}>
                    {getFieldDecorator(`assInfoDtos[${item.id}][id]`, {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: item.id,
                    })(<span>item.id</span>)}
                  </FormItem>
                  <Col span={8}>
                    <FormItem
                      label={
                        <span>
                          减少险种
                          <span style={{ fontSize: '12px', color: '#999' }}>(可多选)</span>
                        </span>
                      }
                      colon={index === 0}
                      {...formItemLayout}
                    >
                      {getFieldDecorator(`assInfoDtos[${item.id}][ass]`, {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: item.ass,
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          mode="multiple"
                          style={{ width: '100%' }}
                          showSearch
                          optionFilterProp="children"
                        >
                          {item.assList.map(options => (
                            <Option key={options.ass} value={options.ass}>
                              {options.assName}
                            </Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem label="业务结束日期" {...formItemLayout}>
                      {getFieldDecorator(`assInfoDtos[${item.id}][endDate]`, {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: item.endDate && moment(item.endDate),
                      })(
                        <MonthPicker
                          placeholder="请选择"
                          style={{ width: '100%' }}
                          onChange={(date, dateString) =>
                            this.selectEndDate(date, dateString, item.id)
                          }
                          format={`YYYY-MM-${item.lastDay}`}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={2}>
                    <MinusCircleOutlined
                      onClick={() => this.deleteList(item.id)}
                      style={{ cursor: 'pointer', position: 'relative', top: 8, fontSize: '16px' }}
                    />
                  </Col>
                </Row>
              ))}
              <Row gutter={16}>
                <Col span={16}>
                  <FormItem>
                    <Button type="dashed" onClick={this.addList} style={{ width: '100%' }}>
                      <PlusOutlined /> 添加
                    </Button>
                  </FormItem>
                </Col>
                <Col span={8} style={{ position: 'relative', top: 8, color: '#999' }}>
                  说明：如果险种业务结束日期不同，可点击添加
                </Col>
              </Row>
            </Card>
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 8 }}>
                取消
              </Button>
              <Button type="primary" onClick={this.submit}>
                提交
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
